<script setup>
import Aliplayer from 'aliyun-aliplayer'
import 'aliyun-aliplayer/build/skins/default/aliplayer-min.css'
import { getCameraListApi } from '@/apis/user'
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useIndexStore } from '@/stores/index'
import { closeDialog, showDialog, showToast } from 'vant'
const indexStore = useIndexStore()

const route = useRoute()
const router = useRouter()

// 当前是否是pc端
const IsPC = () => {
  var userAgentInfo = navigator.userAgent
  var Agents = new Array('Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod')
  var flag = true
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false
      break
    }
  }
  return flag
}

const ispc = (indexStore.ispc = IsPC())

let { id } = route.query

let cid = ref(id),
  ctitle = ref(''),
  curl = ref('')

// 当前权限列表
let cameraList = reactive([])

// 其他区域摄像机列表
// let otherlist = reactive([])

// let timer = ref(null)
// // 检测监控链接是否过期
// const checkCameraUrlIsValid = (dateat) => {
//     let now = parseInt(new Date().getTime() / 1000)
//     if (now > Number(dateat)) {
//         // 过期
//         showDialog({
//             message: '监控链接已过期，请刷新页面重新获取',
//             theme: 'round-button',
//         }).then(() => {
//             // on close
//             // otherlist = []
//             getCameraList()
//         });
//         clearInterval(timer.value)
//     }
// }

let player = ref(null)
let isloading = ref(false) //是否加载中

// 创建播放器
let createPlayer = (url) => {
  player.value = new Aliplayer({
    id: 'playerCont',
    width: '100%',
    height: '100%',
    autoplay: true,
    language: 'en-us',
    source: url,
    isLive: true,
    useH5Prism: true, //启用H5播放器
    playsinline: true,
    preload: true,
    // mute: true, //静音
    controlBarVisibility: 'always',
    skinLayout: [
      {
        name: 'bigPlayButton',
        align: 'blabs',
        x: 30,
        y: 80
      },
      {
        name: 'errorDisplay',
        align: 'tlabs',
        x: 0,
        y: 0
      },
      {
        name: 'infoDisplay'
      },
      {
        name: 'controlBar',
        align: 'blabs',
        x: 0,
        y: 0,
        children: [
          {
            name: 'liveDisplay',
            align: 'tlabs',
            x: 15,
            y: 0
          },
          {
            name: 'fullScreenButton',
            align: 'tr',
            x: 60,
            y: 0
          }
          // {
          //     name: "volume",
          //     align: "tr",
          //     x: 5,
          //     y: 10
          // }
        ]
      }
    ]
  })

  // 数据缓冲事件
  player.value.on('waiting', () => {
    console.log('缓冲中')
    isloading.value = true
  })
  // 数据加载完成事件
  player.value.on('canplay', () => {
    console.log('可以播放')
    isloading.value = false
  })
  // 错误事件
  player.value.on('error', () => {
    console.log('错误')
    isloading.value = false
  })
}

// 获取token
const token = localStorage.getItem('token')

// 查询当前用户数据权限列表
const getCameraList = async () => {
  const res = await getCameraListApi({ token })
  if (res.data.code === 200) {
    cameraList = res.data.data.streams
    cameraList.forEach((item) => {
      if (item.tag === cid.value) {
        ctitle.value = item.push_name_en
        curl.value = item.player_m3u8_url
        // 监控过期时间
        // let cameraUrlDateTo = item.expire_at
        // timer.value = setInterval(() => {
        //     checkCameraUrlIsValid(cameraUrlDateTo)
        // }, 60 * 1000)
      } else {
        // otherlist.push(item)
      }
    })
  } else {
    showToast(res.data.msg)
  }
}
if (token) {
  getCameraList()
} else {
  showToast('请先登录')
  router.replace('/cn')
}

let isplay = ref(false) //是否播放
// 点击播放
const playvideo = () => {
  // console.log(curl.value);
  if (curl.value) {
    isplay.value = true
  }
  if (player.value) {
    player.value.dispose()
  }
  // 请求后台拉取直播流
  // openLive()
  createPlayer(curl.value)
}

const changeCamera = (id, name, url) => {
  ctitle.value = name
  curl.value = url
  isplay.value = false
}

let time = ref(10 * 60) //10分钟
let intervalId = ref(null)
let waitTime = ref(time.value)

const initCountdown = () => {
  if (intervalId.value) {
    clearInterval(intervalId.value)
  }
  intervalId.value = setInterval(handleCountdown, 1000)
  const body = document.querySelector('#live')
  body.addEventListener('click', resetCountdown)
  body.addEventListener('keydown', resetCountdown)
  body.addEventListener('mousemove', resetCountdown)
  body.addEventListener('mousewheel', resetCountdown)
}

const handleCountdown = () => {
  waitTime.value--
  // 倒计时结束
  if (waitTime.value <= 0) {
    doInspection()
    if (intervalId.value) {
      clearInterval(intervalId.value)
    }
  }
}

const doInspection = () => {
  let openin = ref(0)
  let showtimer = ref(null)
  showDialog({
    message: 'The live streaming link has expired. Please refresh the page and retrieve it again',
    theme: 'round-button',
    confirmButtonText: 'Confirm'
  }).then(() => {
    // on close
    openin.value = 1
    clearTimeout(showtimer.value)
    // 重置
    resetCountdown()
  })
  if (openin.value === 0) {
    // 弹窗后10分钟未关闭则回到上一页
    showtimer.value = setTimeout(
      () => {
        clearTimeout(showtimer.value)
        clearInterval(intervalId.value)
        router.replace('/cn/map_local')
        closeDialog()
      },
      10 * 60 * 1000
    )
  }
}

// 重置倒计时
const resetCountdown = () => {
  waitTime = ref(time.value)
  if (intervalId.value) {
    clearInterval(intervalId.value)
  }
  intervalId.value = setInterval(handleCountdown, 1000)
}

onMounted(() => {
  // 页面检测 进入页面10分钟后，出提示，提示后10分钟未关闭则回到上一页
  initCountdown()
})

onUnmounted(() => {
  clearInterval(intervalId.value)
})
</script>

<template>
  <div class="live box bg3 clmcenter" id="live">
    <div class="controlbox">
      <img
        src="@/assets/img/back.png"
        class="btn_goback"
        @click="$router.replace('/en/map_local')"
      />
      <img src="@/assets/img/menu.png" class="btn_menu" @click="$router.replace('/en/main')" />
    </div>
    <img src="@/assets/img/logo.png" class="logo" alt="logo" />
    <div class="container clmstart">
      <div class="stitle stitle_en">
        <img src="@/assets/img/title_left.png" class="title_left anileft" />
        <p>Site Visit</p>
        <img src="@/assets/img/title_right.png" class="title_right aniright" />
      </div>
      <!-- 一个点位 -->
      <div class="camerabox onepointbox clmstart" :style="{ marginTop: ispc ? '' : '1.5vw' }">
        <div class="livevideobox clmcenter">
          <img src="@/assets/img/live1.png" class="liveposter" v-show="!isplay" />
          <img src="@/assets/img/livebox.png" class="livewrapper" />
          <img
            src="@/assets/img/btn_play.png"
            class="playbtn"
            v-show="!isplay"
            @click="playvideo"
          />
          <div class="camerasource" id="playerCont"></div>
          <van-loading
            color="#00B9A2"
            style="z-index: 9"
            text-color="#ffffff"
            vertical
            v-show="isloading"
            >loading</van-loading
          >
        </div>
        <div class="livetitle" :style="{ marginTop: ispc ? '' : '1vw' }">
          <img src="@/assets/img/border-left.png" class="border_left" />
          <p>{{ ctitle }}</p>
          <img src="@/assets/img/border-right.png" class="border_right" />
        </div>
      </div>
      <!-- 底部按钮区 -->
      <div class="otherareabox" :style="{ marginTop: ispc ? '' : '1vw' }">
        <!-- { width: ispc ? '9vw' : '10vw', margin: ispc ? '0 0.3vw' : '0 0.1vw' } -->
        <button
          type="button"
          class="btn"
          v-for="item in cameraList"
          :key="item.tag"
          @click="changeCamera(item.tag, item.push_name_en, item.player_m3u8_url)"
        >
          {{ item.push_name_en }}
        </button>
      </div>
      <!-- 两个点位 -->
      <!-- <div class="camerabox twopointbox" v-show="!oneflag" :style="{ marginTop: ispc ? '' : '4vw' }">
                <div class="camerainfobox clmstart">
                    <div class="livevideobox clmcenter">
                        <img src="@/assets/img/live2.png" class="liveposter" />
                        <img src="@/assets/img/livebox.png" class="livewrapper" />
                        <img src="@/assets/img/btn_play.png" class="playbtn" />
                        <div class="camerasource"></div>
                    </div>
                    <div class="livetitle">
                        <img src="@/assets/img/border-left.png" class="border_left" />
                        <p>Left camera</p>
                        <img src="@/assets/img/border-right.png" class="border_right" />
                    </div>
                </div>
                <div class="areatitle areatitle_en">{{ title }}</div>
                <div class="camerainfobox clmstart">
                    <div class="livevideobox clmcenter">
                        <img src="@/assets/img/live3.png" class="liveposter" />
                        <img src="@/assets/img/livebox.png" class="livewrapper" />
                        <img src="@/assets/img/btn_play.png" class="playbtn" />
                        <div class="camerasource"></div>
                    </div>
                    <div class="livetitle">
                        <img src="@/assets/img/border-left.png" class="border_left" />
                        <p>Right camera</p>
                        <img src="@/assets/img/border-right.png" class="border_right" />
                    </div>
                </div>
            </div> -->
    </div>
  </div>
</template>

<style lang="scss" scoped>
.live {
  overflow: hidden scroll;
  .container {
    position: relative;
    width: 100%;
    .stitle_en {
      p {
        padding: 0 3vw;
      }
    }
    .camerabox {
      .livetitle {
        display: flex;
        justify-content: center;
        align-items: center;
        p {
          font-size: 1.25vw;
          color: #ffffff;
        }
        .border_left {
          width: 0.677vw;
          height: 1.979vw;
          margin-right: 0.36vw;
        }
        .border_right {
          width: 1.51vw;
          height: 1.979vw;
          margin-left: -0.52vw;
        }
      }
    }
    .onepointbox,
    .twopointbox {
      .livevideobox {
        position: relative;
        filter: drop-shadow(0.2vw 0.65vw 0.4vw rgba(0, 0, 0, 0.3));
        .liveposter {
          position: relative;
          z-index: 2;
          width: 100%;
          height: 100%;
          pointer-events: none;
        }
        .livewrapper {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          z-index: 2;
          pointer-events: none;
        }
        .playbtn {
          position: absolute;
          z-index: 3;
          width: 4.9vw;
          cursor: pointer;
        }
        .camerasource {
          position: absolute;
          z-index: 1;
          top: 0;
          left: 0;
          background-color: #000;
          overflow: hidden;
        }
      }
    }
    .onepointbox {
      margin-top: 3.385vw;
      .livevideobox {
        width: 48.07vw;
        height: 27.14vw;
        .camerasource {
          width: 48.07vw;
          height: 27.14vw;
          clip-path: polygon(
            3.542vw 0,
            100% 0,
            100% calc(100% - 3.542vw),
            calc(100% - 3.542vw) 100%,
            0 100%,
            0 3.542vw,
            3.542vw 0
          );
        }
      }
      .livetitle {
        margin-top: 1.09vw;
      }
    }
    .otherareabox {
      width: 100vw;
      margin-top: 3.49vw;
      display: flex;
      justify-content: center;
      align-items: center;
      button {
        // width: 9vw;
        height: 2.24vw;
        font-size: 0.76vw;
        margin: 0 0.3vw;
        line-height: 1.2;
        padding: 0 0.6vw;
      }
    }
    .twopointbox {
      margin-top: 5.9375vw;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      .camerainfobox {
        .livevideobox {
          width: 35.1vw;
          height: 19.79vw;
          .camerasource {
            width: 35.1vw;
            height: 19.79vw;
            clip-path: polygon(
              2.29vw 0,
              100% 0,
              100% calc(100% - 2.29vw),
              calc(100% - 2.29vw) 100%,
              0 100%,
              0 2.29vw,
              2.29vw 0
            );
          }
        }
        .livetitle {
          margin-top: 1.67vw;
        }
      }
      .areatitle {
        margin: 7.55vw 1.6vw 0 2vw;
        font-size: 1.7vw;
        color: #ffffff;
        letter-spacing: 0.7vw;
        text-align: center;
        line-height: 1.3;
      }
      .areatitle_en {
        letter-spacing: 0;
      }
    }
  }
}
</style>
